<?php

namespace \teamug\generation;

class Generator {
  
  
  public static function dataStructuresFromMysql($databaseId) {
    $db = mysqli::getConnection($databaseId);
    list($namespace, $directory) = Project::getAppNamespace();
    self::ensureDirectory("$directory/modelling/", 0755);
    self::ensureDirectory("$directory/modelling/$databaseId", 0755);
    $tables = $db->getColumn('SHOW TABLES');
    foreach($tables AS $table) {
      $kind = Func::stringToName($table);
      $fields = $db->getColumn("DESCRIBE $table");
      $replacements = array(
        'properties' => "  '".\implode("' => '',\n  '", $fields),
        'kind' => $kind,
        'namespace' => "\\$namespace\\modelling\\$databaseId");
      self::writeFromTemplate('DataStructure', "$directory/modelling/$databaseId/$kind.php", $replacements);
    }
  }

  
  public static function dataAccessFromMysql($databaseId) {
    $db = mysqli::getConnection($databaseId);
    list($namespace, $directory) = Project::getAppNamespace();
    self::ensureDirectory("$directory/modelling/", 0755);
    self::ensureDirectory("$directory/modelling/$databaseId", 0755);
    self::ensureDirectory("$directory/modelling/$databaseId/mysql", 0755);
    $tables = $db->getColumn('SHOW TABLES');
    foreach($tables AS $table) {
      $kind = Func::stringToName($table);
      $replacements = array(
        'kind' => $kind,
        'extends' => "\\$namespace\\modelling\\$databaseId\\$kind",
        'namespace' => "\\$namespace\\modelling\\$databaseId\\mysql");
      self::writeFromTemplate('DataAccess', "$directory/modelling/$databaseId/mysql/$kind.php", $replacements);
    }
    
  }


  public static function writeRequestHandlers($pages) {
    
    list($namespace, $directory) = Project::getAppNamespace();
    
    foreach($pages AS $page) {
      $class_name = Func::stringToName($page);
      $replacements = array(
        'class_name'=>$class_name,
        'namespace'=>$namespace
      );
      self::writeFromTemplate('RequestHandler', "$directory/$class_name.php", $replacements);
    }
    self::writeFromTemplate('SiteRequestHandler', "$directory/RequestHandler.php", $replacements);
  }
  
  
  
  private static function ensureDirectory($dir, $perm) {
    
    if (!\file_exists($dir)) {
      $created = \mkdir($dir, $perm);
      if (!$created) { exit("Directory:$dir could not be created. Check permissions etc.<br/>\n"); }
    }
  }
    
    
  private static function writeFromTemplate($template, $destination, $replacements=array()) {
    
    $code = \file_get_contents("tpl_$template");
    
    foreach($replacements AS $key => $value) {
      $code = \str_replace("___{$key}___", $value, $code);
    }
    
    $fp = fopen($destination, 'w');
    $byte_cnt = fwrite($fp, $content);
    fclose($fp);
  }
}
